package io.zhiller.ollamaclient.utils

import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale
import io.zhiller.ollamaclient.ui.component.BottomDrawerInfoButton

object PermissionUtils {
  
  data class PermissionInfo(
    val permission: String,
    val permissionName: String,
  )
  
  @OptIn(ExperimentalPermissionsApi::class)
  @Composable
  fun RequestPermissionEffect(
    permissionInfo: PermissionInfo,
    showBottomDrawer: Boolean = false,
    onSuccess: () -> Unit = {},
    onFailure: () -> Unit = {},
  ) {
    val context = LocalContext.current
    
    var isDrawerOpen by remember { mutableStateOf(false) }
    
    // 请求存储权限
    val permissionState = rememberPermissionState(permission = permissionInfo.permission)
    
    LaunchedEffect(permissionState.status) {
      when {
        permissionState.status.isGranted -> {
          // 权限已授予，调用 onSuccess
          onSuccess()
        }
        
        permissionState.status.shouldShowRationale -> {
          // 需要显示权限请求理由，调用 onFailed
          if (showBottomDrawer) {
            isDrawerOpen = true
          } else {
            Toast.makeText(
              context,
              "请至应用设置界面允许${permissionInfo.permissionName}权限",
              Toast.LENGTH_SHORT
            ).show()
          }
          onFailure()
        }
        
        else -> {
          // 权限未授予，请求权限
          permissionState.launchPermissionRequest()
        }
      }
    }
    
    if (isDrawerOpen) {
      BottomDrawerInfoButton(title = "${permissionInfo.permissionName}权限被拒绝",
        content = "请点击下面按钮前往应用设置界面，允许${permissionInfo.permissionName}权限\n该权限对后续的功能有影响",
        buttonTitle = "前往应用设置",
        onDismissRequest = { isDrawerOpen = false },
        onConfirm = {
          IntentUtils.openAppSettings(context)
          isDrawerOpen = false
        })
    }
  }
  
  @OptIn(ExperimentalPermissionsApi::class)
  @Composable
  fun RequestPermissionsEffect(
    permissionInfo: List<PermissionInfo> = emptyList(),
    showBottomDrawer: Boolean = false,
    onSuccess: () -> Unit = {},
    onFailure: () -> Unit = {},
  ) {
    val context = LocalContext.current
    
    var isDrawerOpen by remember { mutableStateOf(false) }
    
    // 获取权限列表
    val permissions = permissionInfo.map { it.permission }
    
    // 使用 rememberMultiplePermissionsState 管理多个权限状态
    val permissionsState = rememberMultiplePermissionsState(permissions = permissions)
    
    // 提取 permissionName 并连接成字符串
    val permissionsNames = permissionInfo.joinToString(", ") { it.permissionName }
    
    LaunchedEffect(permissionsState.permissions) {
      if (permissionsState.allPermissionsGranted) {
        // 所有权限已授予，调用 onSuccess
        onSuccess()
      } else {
        // 检查是否有权限被拒绝
        val shouldShowRationale = permissionsState.permissions.any { it.status.shouldShowRationale }
        if (shouldShowRationale) {
          // 需要显示权限请求理由，调用 onFailure
          if (showBottomDrawer) {
            isDrawerOpen = true
          } else {
            Toast.makeText(context, "请至应用设置界面允许相关权限", Toast.LENGTH_SHORT).show()
          }
          onFailure()
        } else {
          // 请求权限
          permissionsState.launchMultiplePermissionRequest()
        }
      }
    }
    
    if (isDrawerOpen) {
      BottomDrawerInfoButton(title = "部分权限被拒绝",
        content = "请检查${permissionsNames}\n是否有遗漏未授权的权限",
        buttonTitle = "前往应用设置",
        onDismissRequest = { isDrawerOpen = false },
        onConfirm = {
          IntentUtils.openAppSettings(context)
          isDrawerOpen = false
        })
    }
  }
}